import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//二叉树最大宽度
//测试链接 https://leetcode.cn/problems/maximum-width-of-binary-tree/description/
public class WidthOfBinaryTree {

    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
   }

    class Pair {
        TreeNode node;
        int x;

        Pair() {}
        Pair(TreeNode node, int x) {
            this.node = node;
            this.x = x;
        }
    }

    public int widthOfBinaryTree(TreeNode root) {
        int ret = 0;
        if(root == null) return ret;

        Queue<Pair> q = new LinkedList<>();
        Pair pair = new Pair(root,1); //给每个节点编号，从1开始
        q.add(pair);
        ret = 1;
        while(!q.isEmpty()) {
            int size = q.size();

            List<Integer> list = new ArrayList<>(); //存放每一层节点对应的序号
            for(int i = 0; i < size; i++) {
                Pair p  = q.poll();
                int parent = p.x;  //父亲节点的值

                if(p.node.left != null) {
                    q.add(new Pair(p.node.left,parent*2) );
                    list.add(parent*2);
                }

                if(p.node.right != null) {
                    q.add(new Pair(p.node.right, parent*2 + 1) );
                    list.add(parent*2 + 1);
                }
            }
            if(!list.isEmpty()) {
                int begin = list.get(0);
                int end = list.get(list.size() - 1);
                if(end - begin + 1 > ret) {
                    ret = end - begin + 1;
                }
            }
        }

        return ret;
    }
}
